/**
 * 数据视图组件
 */
import React, { Component,Fragment } from 'react';
import { Form, Icon, Row, Col, Button } from 'antd';

import { isEmpty,isNull,isNotNull } from '../common';
import { getUIForm } from '../uiConfig';

import UIFormField from './UIFormField';
import UIDataList from './UIDataList';
import UIDataTable from './UIDataTable';
import UIDataTree from './UIDataTree';
import UIView from './UIView';
import UIDragDataTable from "./UIDragDataTable";

class UIDataSearchFormComponent extends Component {
    constructor(props) {
        super(props);
        this.searchFormFields = [];
        this.state = {
            expandForm: false,
            searchData: {},
            searchFormParams : props.params,
            initSearchValues : props.initSearchValues,
        };
    }

    getFields(searchFormFields) {

        const count = this.state.expandForm ? searchFormFields.searchFormFields.length : 3;

        const children = [];

        let span = parseInt((24-8)/searchFormFields.searchFormFields.length,0);
        // console.log("间隔：",span);
        for (let i = 0; i < searchFormFields.searchFormFields.length; i++) {
            children.push(
                <Col span={span} key={i} style={{ display: i < count ? 'block' : 'none' }}>
                    {searchFormFields.searchFormFields[i]}
                </Col>
            );
        }

        return children;
    }

    toggleForm = () => {
        this.setState({
            expandForm: !this.state.expandForm,
        });
    }

    clearForm = () => {
        const { form } = this.props;
        form.resetFields();
    }

    handleFormReset = () => {
        const { form } = this.props;

        this.setState({initSearchValues : {}});

        setTimeout(() => {
            form.resetFields();
            form.validateFields((err, values) => {
                if (err) {
                    return;
                }

                if (this.props.handleFormReset !== undefined) {
                    this.props.handleFormReset(values);
                }

            });
        });
    }

    dosearch = () => {
        const { form } = this.props;

        form.validateFields((err, values) => {
            if (err) {
                return;
            }

            if (this.props.handleSearch !== undefined) {
                this.props.handleSearch(values);
            }

        });
    }

    handleSearch = (e) => {
        e.preventDefault();
        this.dosearch();
    }

    setSearchFormFieldParams = (fieldId,params) => {
        this.searchFormFields.forEach( (filed) => {
            if(fieldId === filed.props.id){
                filed.setParams(params);
            }
        } );
    }

    setSearchFormParams = (params) => {
        this.setState({searchFormParams : params});
        setTimeout(() => {
            this.searchFormFields.forEach( (filed) => {
                filed.updateFormFiled();
            } );
        });
    }

    render() {

        const { getFieldDecorator } = this.props.form;

        const {searchFormParams,initSearchValues} = this.state;

        const searchFormConfig = isEmpty(this.props.searchFormId) === false ? getUIForm(this.props.searchFormId) : null;

        const searchFormFields = isNull(searchFormConfig) === true ? [] : searchFormConfig.formProperties.map((formField,index) => {
            return <UIFormField 
                id={formField.id} 
                key={formField.id} 
                ref={(inst) => this.searchFormFields[index] = inst} 
                params={searchFormParams} 
                initialValue={isNull(initSearchValues) === false ? initSearchValues[formField.id] : null} 
                formField={formField} 
                fieldDecorator={getFieldDecorator} 
            />;
        });

        const showExpandForm = searchFormFields.length > 3 ? true : false;

        return (
            <Fragment>
                {
                    isEmpty(this.props.searchFormId) === false ?
                        (
                            <div className="tableListForm">
                                <Form onSubmit={this.handleSearch} >
                                    {/* <Row gutter={24}>{this.getFields({ searchFormFields })}</Row>
                                    <Row>
                                        <Col span={24} style={{ textAlign: 'right' }}>
                                            <Button type="primary" htmlType="submit">查询</Button>
                                            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                                                重置
								            </Button>
                                            {showExpandForm &&
                                                <a style={{ marginLeft: 8, fontSize: 12 }} onClick={this.toggleForm}>
                                                    {this.state.expandForm ? '收起' : '展开'} <Icon type={this.state.expandForm ? 'up' : 'down'} />
                                                </a>
                                            }
                                        </Col>
                                    </Row> */}
                                    <Row gutter={8}>
                                        {this.getFields({ searchFormFields })}
                                        {/* <Col span={24-(searchFormFields.length*8)} > */}
                                        <Col span={8} >
                                            <Button type="primary" htmlType="submit">查询</Button>
                                            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                                                重置
								            </Button>
                                            {showExpandForm &&
                                                <a style={{ marginLeft: 8, fontSize: 12 }} onClick={this.toggleForm}>
                                                    {this.state.expandForm ? '收起' : '展开'} <Icon type={this.state.expandForm ? 'up' : 'down'} />
                                                </a>
                                            }
                                        </Col>
                                    </Row>
                                </Form>
                            </div>
                        ) : null
                }
            </Fragment>
        );
    }
}

const UIDataSearchForm = Form.create({
    onValuesChange : (props, changedValues, allValues) => {
        if(props.onValuesChange !== undefined){
            props.onValuesChange(changedValues, allValues);
        }
    }
})(UIDataSearchFormComponent);

const WarpUIView = UIDataComponent => {
    class WarpedComponent extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                selectRowKeys: [],
                searchData: {},
            };
        }

        componentDidMount() {
            const { innerView } = this.refs;
            const { toolbar } = innerView.refs;
            const {setToolbarState } = this.props;

            if (setToolbarState !== undefined && toolbar) {
                setToolbarState(toolbar, innerView);
            }

            if (this.props.autoLoad) {
                if(isNull(this.searchForm) === false){
                    this.searchForm.dosearch();
                }
                else{
                    this.loadData({});
                }
            }

            if (this.props.onLoadData !== undefined) {
                this.props.onLoadData(this);
            }
        }

        handleFormReset = (values) => {
            const { dataComponent } = this.refs;
            //this.setState({searchData: {}});
            if (dataComponent.searchData) {
                values.current = 1;
                dataComponent.searchData({ ...values, ...this.params });
            }

            if (this.props.onSearchData !== undefined) {
                this.props.onSearchData({ ...values, ...this.params });
            }
        }

        clearForm = () => {
            this.searchForm.clearForm();
        }

        handleSearch = (values) => {
            const { dataComponent } = this.refs;
            if (dataComponent.searchData) {
                values.current = 1;
                dataComponent.searchData({ ...values, ...this.params });
            }

            if (this.props.onSearchData !== undefined) {
                this.props.onSearchData(values);
            }
        }

        /**
         * @param  params 加载数据参数
         * @param  clearSelected 是否清空选择
         */
        loadData = (params, clearSelected = true) => {

            const { dataComponent } = this.refs;

            this.params = params;

            if (clearSelected) {
                this.clearSelected();
            }

            if (isNull(this.searchForm) !== true) {
                const { form } = this.searchForm.props;
                form.validateFields((err, values) => {
                    if (err) {
                        return;
                    }
                    dataComponent.searchData({ ...values, ...params });
                });
            }
            else if(isNotNull(dataComponent)) {
                dataComponent.searchData(params);
            }
        }

        setSearchFormParams = (params) => {
            this.searchForm.setSearchFormParams(params);
        }

        onSelectChange = (selectRowKeys, node) => {
            const { innerView,dataComponent } = this.refs;
            const { toolbar } = innerView.refs;
            const { setToolbarState, onSelectChange } = this.props;

            this.setState({ selectRowKeys: selectRowKeys });

            if(isNotNull(dataComponent)){
                dataComponent.setSelectedRowKeys(selectRowKeys);
            }
           
            if (onSelectChange) {
                setTimeout(function () {
                    onSelectChange(selectRowKeys, node);
                });
            }

            if (isNotNull(toolbar) && setToolbarState) {
                setTimeout(function () {
                    setToolbarState(toolbar, selectRowKeys, node, innerView);
                });
            }
        }

        setListData = (listData,clearSelected = true) => {
            const { dataComponent } = this.refs;
            dataComponent.setListData(listData);
            if (clearSelected) {
                this.clearSelected();
            }
        }

        getListData = () => {
            const { dataComponent } = this.refs;
            return dataComponent.getListData();
        }

        getSelected = () => {
            const { dataComponent } = this.refs;
            return dataComponent.getSelectedRowKeys();
        }

        getSelectedDatas = () => {
            const { dataComponent } = this.refs;
            return dataComponent.getSelectedDatas();
        }

        setSelected = (rowIds, node) => {
            this.onSelectChange(rowIds, node);
        }

        clearSelected = () => {
            const { dataComponent } = this.refs;
            //console.log(dataComponent);
            if (isNotNull(dataComponent) && isNotNull(dataComponent.clearSelectedRowKeys)) {
                dataComponent.clearSelectedRowKeys();
            }

            this.onSelectChange([]);
        }

        isOpend = () => {
            const { innerView } = this.refs;
            return innerView.isOpend();
        }

        closeModal = (e) => {
            const { innerView } = this.refs;
            innerView.closeModal();
        }

        openModal = (cb) => {
            const { innerView } = this.refs;
            innerView.openModal(cb);
        }

        setTableConfig = (data) => {
            const { dataComponent } = this.refs;
            dataComponent.setTableConfig(data)
        }

        enableDragTable = (canDrag) => {
            const { dataComponent } = this.refs;
            dataComponent.enableDragTable(canDrag)
        }


        render() {
            
            const topContent = (
                <Fragment>
                    {
                        isEmpty(this.props.searchFormId) === false ?
                            (
                                <UIDataSearchForm
                                    params={this.props.params}
                                    wrappedComponentRef={(inst) => this.searchForm = inst}
                                    searchFormId={this.props.searchFormId}
                                    handleSearch={this.handleSearch}
                                    handleFormReset={this.handleFormReset} 
                                    onValuesChange={this.props.onSearchFormValueChange}
                                    initSearchValues={this.props.initSearchValues}
                                    />
                            ) : null
                    }
                </Fragment>
            );

            const dataComponentProps = {
                ref: 'dataComponent',
                onSelectChange: this.onSelectChange,
                autoLoad : isEmpty(this.props.searchFormId) === true ? this.props.autoLoad : false,
            }

            return (
                <UIView bordered={false} {...this.props} topContent={topContent} parent={this} ref="innerView">
                    <UIDataComponent {...this.props} {...dataComponentProps} />
                    {this.props.children}
                </UIView>
            );
        }
    };

    return WarpedComponent;
};

export const UIDataTableView = WarpUIView(UIDataTable);
export const UIDataListView = WarpUIView(UIDataList);
export const UIDataTreeView = WarpUIView(UIDataTree);
export const UIDragDataTableView = WarpUIView(UIDragDataTable);
